<?php

namespace app\commission;

use app\award\Award;
use app\award\Up;
use app\controllers\admin\uni\order\OrderController;
use app\controllers\h5\uni\ExpressApi;
use app\controllers\h5\uni\ExpressApiController;
use app\controllers\pay\ForController;
use app\controllers\wx\services\Template;
use app\models\AdminSupplier;
use app\models\ExpressCallback;
use app\models\group\Group;
use app\models\group\GroupFans;
use app\models\marketing\MarketingGroup;
use app\models\merchant\MerchantPayFor;
use app\models\order\Order;
use app\models\merchant\MerchantOrder;
use app\models\order\OrderItem;
use app\models\pay\Pay;
use app\models\product\Product;
use app\models\product\ProductArea;
use app\models\Queue;
use app\models\user\User;
use app\models\user\UserAccount;
use app\models\user\UserCommission;
use app\models\user\UserConsume;
use app\models\UserBalance;
use app\models\UserStore;
use app\models\UserStoreLog;
use app\util\Debug;
use yii\base\BaseObject;

/**
 * order & merchant paid
 *
 * Class PaidFinish
 * @package app\commission
 */
class PaidFinish
{
    /**
     * wx pay paid
     *
     * @param Pay $pay
     */
    public static function paidRun(Pay $pay)
    {
        $transaction = \Yii::$app->db->beginTransaction();

        try {

            $order = Order::findOne(['sn' => $pay->sn]);

            // var_dump($order);exit;

            if ($order) {
                self::order($order);
            }

            $transaction->commit();

        } catch (\Exception $e) {

            $transaction->rollBack();
            Debug::debug('paid-finish-error', $e->getMessage());
        }
    }

    // order paid (order & group)
    public static function order(Order $order)
    {
        // todo 这里可能需要判断订单 此时的状态为 待支付
        // todo 否则, 如果支付多次, 返佣则会重复

        // order status
        $order->status = Order::$statusMapping['PAID'];

        // 如果是商家订单改成 待核销
        // 并且是线下店
        if ($order->supplier_id > 0) {
            $s = AdminSupplier::findOne(['id' => $order->supplier_id]);
            if ($s->is_shop == 1) {
                $order->status = Order::$statusMapping['MERCHANT'];
            }
        }

        // 如果是进云仓订单
        if ($order->is_store) {
            $order->status = Order::$statusMapping['FINISH'];
        }

        $order->save();

        // account
        $account = UserAccount::findOne(['user_id' => $order->user_id]);
        if ($order->use_balance > 0) {

            // 改成锁定的余额了
            // $account->balance -= $order->use_balance;
            $account->lock_balance -= $order->use_balance;
        }
        if ($order->use_score > 0) {
            // $account->score -= $order->use_score;
            $account->lock_score -= $order->use_score;
        }
        if ($order->use_ticket > 0) {
            // $account->ticket -= $order->use_ticket;
            $account->lock_ticket -= $order->use_ticket;
        }
        if ($order->use_platform_ticket > 0) {
            $account->lock_platform_ticket -= $order->use_platform_ticket;
        }
        $account->save();

        // consume
        $consume = new UserConsume();
        $consume->user_id = $order->user_id;
        if ($order->use_balance > 0) {
            $consume->balance = $order->use_balance;

        }
        // 把联娱券, 定向券的消费, 记录到消费表
        if ($order->use_score > 0) {
            $consume->score = $order->use_score;
        }
        if ($order->use_ticket > 0) {
            $consume->ticket = $order->use_ticket;
        }

        // if ($order->use_score > 0) {
        //     $consume->score = $order->use_score;
        // }
        if ($order->use_platform_ticket > 0) {
            $consume->platform_ticket = $order->use_platform_ticket;
        }
        $consume->order_id = $order->id;
        $consume->status = 1;
        $consume->text = '下单';
        // if ($order->is_group == 1) {
        //     $consume->text = '下单(拼团)';
        //
        //     $group_id = Group::find()
        //         ->where(['order_id' => $order->id])
        //         ->select(['id'])
        //         ->scalar();
        //     $consume->group_order_id = $group_id;
        // }
        $consume->save();

        // commission or group action
        // if ($order->is_group == 1) {
        //     // action group
        //     self::group($order);
        // } else {
        //     // commission
        //     // Commission::getInstance()->getOrder()->commission($order);
        // }

        // up level
        // 这里处理了升级和佣金
        // UpLevel::up($order);

        // commission & up
        // new C($order);
        // new C2($order);
        // new U($order);


        // 先返佣, 后升级

        // 返佣
        // new CommissionNew($order);
        //
        // // 升级
        // new UpNew($order);


        // 云仓
        if ($order->is_store == 1) {
            // 去除预警
            User::updateAll(['store_warn' => 0], ['id' => $order->user_id]);

            // 记录到云仓
            $store = UserStore::findOne(['user_id' => $order->user_id]);
            if (!$store) {
                $store = new UserStore();
                $store->user_id = $order->user_id;
                $store->num = 0;
            }

            // 云仓日志
            $store_log = UserStoreLog::addLog($order->user_id, $store->num, $order->store_box, $store->num + $order->store_box,
                '下单', 1);

            $store->num += $order->store_box;
            $store->save();

            // 云仓日志订单号
            if (isset($store_log)) {
                $store_log->order_id = $order->id;
                $store_log->save();
            }
        }

       if ($order->express_area == 0) {
           // stock
           $stock = new Stock($order);
           $stock->run();

           // sell count
           $items = OrderItem::find()
               ->where(['order_id' => $order->id])
               ->all();
           foreach ($items as $item) {
               $p = Product::findOne(['id' => $item->product_id]);
               $p->sell_count += $item['quantity'];
               $p->save();
           }

           // Template::expressOrder($order);
       } else {

           if ($order->total_quantity != 0) {
               // 快递订单, 下单到物流
               $data = json_decode($order->request_params, true);
               $api = new ExpressApi();
               $api->order($data, $order);
           }
       }

       // 如果是增加运费, 补运费数量为0
        if ($order->total_quantity == 0) {

            // var_dump(111);exit;

            $x = json_decode($order->request_params, true);
            $x = Order::findOne(['id' => $x['order_id']]);
            if ($x) {
                $x->add_freight_ok = 1;
                $x->save();
            }

            // 补运费完成
            $order->status = Order::$statusMapping['FINISH'];
            $order->save();

            // 小程序发货
            // OrderController::miniExpress($order->id);

            // 这里用队列处理, 太快了, 小程序不推送
            $queue = new Queue();
            $queue->order_id = $order->id;
            $queue->status = 0;
            // 把原始Order id 放在month中
            // 以防后面, 需要处理物流公司用
            if ($order->request_params) {
                $o_id = json_decode($order->request_params, true);
                $queue->month = $o_id['order_id'];
            }
            $queue->save();


            // 补运费也返佣
            new Award($order);

            // 处理返佣
            // $call = ExpressCallback::findOne(['waybill' => $order->waybill, 'shopbill' => $order->shopbill]);
            $call = ExpressCallback::findOne(['waybill' => $x->waybill, 'shopbill' => $x->shopbill]);
            // var_dump($call->typeCode);exit;
            if ($call && $call->typeCode == 3) {
                // 已签收

                $x->status = Order::$statusMapping['FINISH'];
                $x->save();

                // 这个用来处理普通商品
                // ReceivedCommission::done($order->id);

                $commissions = UserCommission::find()
                    // ->where(['order_id' => $order->id])
                    ->where(['order_id' => $x->id])
                    ->andWhere(['status' => 0])
                    ->all();
                foreach ($commissions as $c) {
                    $c->status = 1;
                    $c->save();

                    $account = UserAccount::findOne(['user_id' => $c->user_id]);
                    if ($account) {
                        if ($account->await_balance >= $c->balance) {

                            UserBalance::addLog($c->user_id,
                                $account->balance, $c->balance, $account->balance + $c->balance, $c->award_name, $c->order_id);

                            $account->await_balance -= $c->balance;
                            $account->done_balance += $c->balance;
                            $account->balance += $c->balance;
                            $account->save();

                            // 消息
                            Template::commission($x, $c->balance, $c->user_id);
                        }
                    }
                }

            }

        } else {
            new Award($order);
            new Up($order);
        }



    }

    // merchant order paid
    // public static function merchant(MerchantOrder $merchantOrder)
    // {
    //     /*
    //      * 1) change merchant order status
    //      * 2) create merchant pay for
    //      * 3) sub account
    //      * 4) add consume
    //      */
    //
    //     $merchantOrder->status = 1;
    //     $merchantOrder->save();
    //
    //     $merchant = \app\models\merchant\Merchant::findOne(['id' => $merchantOrder->merchant_id]);
    //
    //     $amount = $merchantOrder->total * ((100 - $merchant->difference) / 100);
    //
    //     $pay_for = new MerchantPayFor();
    //     $pay_for->sn = MerchantPayFor::generateSn();
    //     $pay_for->user_id = $merchant->user_id;
    //     $pay_for->pay_sn = $merchantOrder->sn;
    //     $pay_for->nickname = $merchant->nickname;
    //     $pay_for->bank_number = $merchant->bank_number;
    //     $pay_for->amount = $amount;
    //     $pay_for->status = 0;
    //     $pay_for->save();
    //
    //     $account = UserAccount::findOne(['user_id' => $merchantOrder->user_id]);
    //     $account->ticket -= $merchantOrder->ticket;
    //     $account->save();
    //
    //     $consume = new UserConsume();
    //     $consume->user_id = $merchantOrder->user_id;
    //     $consume->ticket = $merchantOrder->ticket;
    //     $consume->merchant_order_id = $merchantOrder->id;
    //     $consume->status = 1;
    //     $consume->text = '商家支付';
    //     $consume->save();
    //
    //     // call pay for
    //     ForController::pay(
    //         $pay_for->sn,
    //         $pay_for->user_id,
    //         $pay_for->amount,
    //         $pay_for->bank_number,
    //         $pay_for->nickname,
    //         2,
    //         '付给商家'
    //     );
    // }

    // protected static function group(Order $order)
    // {
    //     // group status
    //     $group = Group::findOne(['order_id' => $order->id]);
    //     if ($group) {
    //         $group->status = 1;
    //         $group->save();
    //     }
    //
    //     // fans status
    //     $fans = GroupFans::findOne(['order_id' => $order->id]);
    //     if ($fans) {
    //         $fans->status = 1;
    //         $fans->save();
    //     }
    //
    //     $params = json_decode($order->request_params);
    //
    //     // join
    //     if (isset($params->group_id) && $params->group_id && $params->group_id > 0) {
    //         self::groupFinish($fans->group_id);
    //     }
    //
    //     // random
    //     if (isset($params->random_group) && $params->random_group) {
    //         self::groupFinish($fans->group_id);
    //     }
    // }
    //
    // protected static function groupFinish($group_id)
    // {
    //     $set = MarketingGroup::getLastOne();
    //     $max = $set->quantity;
    //
    //     $fans_count = GroupFans::find()
    //         ->where(['group_id' => $group_id])
    //         ->andWhere(['status' => 1])
    //         ->count();
    //
    //     if ($fans_count >= $max) {
    //         $group = Group::findOne(['id' => $group_id]);
    //         $group->status = 2;
    //         $group->save();
    //
    //         Commission::getInstance()->getGroup()->commission($group);
    //     }
    //
    // }
}